package priv.hehe.init;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.servlet.Servlet;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class InitServer {
	private static final Logger logger=Logger.getLogger(InitServer.class);
	public static void main(String[] args) {
		try {
			initJetty();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	private static void initJetty() throws Exception, InterruptedException {
		Server server = new Server();//初始化服务
		ServerConnector connect = new ServerConnector(server);//初始化链接
		String port=MainConfig.getString("InitServer.port"); //$NON-NLS-1$
		connect.setPort(Integer.parseInt(port));
		Connector[] connectors = {connect};
		server.setConnectors(connectors);//设置连接
		ContextHandlerCollection handler = new ContextHandlerCollection();
		ServletContextHandler servletContextHandler = new ServletContextHandler();
		servletContextHandler.setContextPath(MainConfig.getString("InitServer.context")); //$NON-NLS-1$
		getServletProperties(servletContextHandler);
		Handler[] handlers = {servletContextHandler,new DefaultHandler()};
		handler.setHandlers(handlers);
		server.setHandler(handler);//设置处理器
		server.start();//开启服务
		server.join();
	}
	
	/**
	 * 配置sevlet，将配置文件中的sevlet加入到jetty容器中区
	 * @param servletContextHandler
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private static void getServletProperties(ServletContextHandler servletContextHandler) 
			throws IOException, ClassNotFoundException{
		Properties properties = new Properties();
		//获取属性配置文件
		InputStream in = Thread.currentThread()
				.getContextClassLoader()
				.getResourceAsStream("sevlet.properties");
		properties.load(in);//加载属性配置文件
		Set<Entry<Object, Object>> entrySet = properties.entrySet();
		for (Entry<Object, Object> entry : entrySet) {
			@SuppressWarnings("unchecked")
			Class<? extends Servlet> clazz = (Class<? extends Servlet>) 
					Class.forName(entry.getValue().toString());
			servletContextHandler.addServlet(clazz, entry.getKey().toString());
		}
	}

}
